<?php

        function isValidApp($app){
            include 'config.php';
            $app = mysqli_real_escape_string($db, $app);
            $query = "SELECT * FROM users WHERE app_key = '$app' AND active = 1;";
            $result = mysqli_query($db, $query);
            if(mysqli_num_rows($result) == 1){
                return true;
            }
            return false;
        }
        
        function logger($service, $status, $application){
            include 'config.php';
            $service = mysqli_real_escape_string($db, $service);
            $status = mysqli_real_escape_string($db, $status);
            $application = mysqli_real_escape_string($db, $application);
            
            $query = "INSERT INTO fhpi_usage (service, status, application) VALUES ('$service', '$status', '$application');";
            mysqli_query($db, $query);
        }
        
	function randstring($length = 8) {
	    $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
	    $string = "";    
	    for ($p = 0; $p < $length; $p++) {
		$string .= $characters[mt_rand(0, strlen($characters)-1)];
	    }
	    return $string;
	}
        
        function getStudents($file, $course, $year){
            // $course = array with name, abbrev and type
            $url = 'http://www.fh-joanneum.at/'.  strtolower($course[1]).'_studierende'.$course[2].'_'.$year;
            
            $f = curl_init($url);
            curl_setopt($f, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($f, CURLOPT_COOKIEFILE, $file[0]);
            curl_setopt($f, CURLOPT_COOKIEJAR, $file[0]);
            curl_setopt($f, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($f, CURLOPT_HEADER, 0);

            $content = curl_exec($f);

            curl_close($f);

            $fh = fopen($file[1], 'w');
            fwrite($fh, $content);
            fclose($fh);
        }

	function getMarks($file, $user, $pass, $locale){
		$url[] = "https://actions.fh-joanneum.at/login.do";
    		$url[] = "https://actions.fh-joanneum.at/j_acegi_security_check";
    		$url[] = "https://actions.fh-joanneum.at/st/listMarks.do?locale=".$locale;
    
    		// First contact to the server: Get the JSESSIONID.
    
		$c = curl_init($url[0]);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_COOKIEFILE, $file[0]);
		curl_setopt($c, CURLOPT_COOKIEJAR, $file[0]);
		curl_setopt($c, CURLOPT_HEADER, 1);
    
		$content = curl_exec($c);

		$cookie = explode("JSESSIONID=", $content);
		$cookie = explode(";", $cookie[1]);
		$cookie = $cookie[0];

		curl_close($c);
    
		$postdata2 = "j_domain=technikum&j_username=$user&submit=Anmelden&j_password=$pass";
    
		$d = curl_init($url[1]);
		curl_setopt($d, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($d, CURLOPT_HEADER, 1);
		curl_setopt($d, CURLOPT_COOKIEFILE, $file[0]);
		curl_setopt($d, CURLOPT_COOKIEJAR, $file[0]);
		curl_setopt($d, CURLOPT_POSTFIELDS, $postdata2);
		curl_setopt($d, CURLOPT_REFERER, $url[0]);
		curl_setopt($d, CURLOPT_POST, 1);
		curl_setopt($d, CURLOPT_FOLLOWLOCATION, true);

		curl_setopt($d, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
		curl_setopt($d, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.04 (lucid) Firefox/3.6.23");
    
		$result = curl_exec($d);

		curl_close($d);

		// Navigate to grades and save the output

		$e = curl_init($url[2]);
		curl_setopt($e, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($e, CURLOPT_COOKIEFILE, $file[0]);
		curl_setopt($e, CURLOPT_COOKIEJAR, $file[0]);
		curl_setopt($e, CURLOPT_HEADER, 0);

		$content = curl_exec($e);

		curl_close($e);

		$fh = fopen($file[1], 'w');
		fwrite($fh, $content);
		fclose($fh);
	}

	function getExams($file, $user, $pass, $locale){
		$url[] = "https://actions.fh-joanneum.at/login.do";
    		$url[] = "https://actions.fh-joanneum.at/j_acegi_security_check";
    		$url[] = "https://actions.fh-joanneum.at/exams/administration.do?locale=".$locale;
    
    		// First contact to the server: Get the JSESSIONID.
    
		$c = curl_init($url[0]);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_COOKIEFILE, $file[0]);
		curl_setopt($c, CURLOPT_COOKIEJAR, $file[0]);
		curl_setopt($c, CURLOPT_HEADER, 1);
    
		$content = curl_exec($c);

		$cookie = explode("JSESSIONID=", $content);
		$cookie = explode(";", $cookie[1]);
		$cookie = $cookie[0];

		curl_close($c);
    
    // Second contact to the server: Send Login-Data
    
    //$postdata["j_domain"] = "technikum";
    //$postdata["j_username"] = $username;
    //$postdata["submit"] = "Anmelden";
    //$postdata["j_password"] = $password;
    
		$postdata2 = "j_domain=technikum&j_username=$user&submit=Anmelden&j_password=$pass";
    
		$d = curl_init($url[1]);
		curl_setopt($d, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($d, CURLOPT_HEADER, 1);
		curl_setopt($d, CURLOPT_COOKIEFILE, $file[0]);
		curl_setopt($d, CURLOPT_COOKIEJAR, $file[0]);
		curl_setopt($d, CURLOPT_POSTFIELDS, $postdata2);
		curl_setopt($d, CURLOPT_REFERER, $url[0]);
		curl_setopt($d, CURLOPT_POST, 1);
		curl_setopt($d, CURLOPT_FOLLOWLOCATION, true);

		curl_setopt($d, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
		curl_setopt($d, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.04 (lucid) Firefox/3.6.23");
    
		$result = curl_exec($d);

		curl_close($d);

		// Navigate to grades and save the output

		$e = curl_init($url[2]);
		curl_setopt($e, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($e, CURLOPT_COOKIEFILE, $file[0]);
		curl_setopt($e, CURLOPT_COOKIEJAR, $file[0]);
		curl_setopt($e, CURLOPT_HEADER, 0);

		$content = curl_exec($e);

		curl_close($e);

		$fh = fopen($file[1], 'w');
		fwrite($fh, $content);
		fclose($fh);
	}

	function objectsIntoArray($arrObjData, $arrSkipIndices = array()){
		$arrData = array();
		// if input is object, convert into array
		if (is_object($arrObjData)) {
		    $arrObjData = get_object_vars($arrObjData);
		}

		if (is_array($arrObjData)) {
		    foreach ($arrObjData as $index => $value) {
		        if (is_object($value) || is_array($value)) {
		            $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
		        }
		        if (in_array($index, $arrSkipIndices)) {
		            continue;
		        }
		        $arrData[$index] = $value;
		    }
		}
		return $arrData;
	}

	function parseMarks($file){
    		$fh = fopen($file[1], "r");
    
		$content = fread($fh, filesize($file[1]));

		fclose($fh);
    
		$content = explode("marksTable", $content);

		$content = '<table cellpadding="3" cellspacing="0" class="list" id="'.$content[1];

		$content = explode('<div class="fnotes">', $content);

		$content = trim($content[0]);

		$content = str_replace("&nbsp;", "", $content);
		$content = str_replace("\t", "", $content);
		$content = str_replace("\n", "", $content);
		$content = str_replace("\r", "", $content);
		$content = str_replace("</td></td>", "</td>", $content);
		$content = str_replace("&Uuml;", "Ü", $content);

		$content = '<?xml version="1.0"?>'.$content;
    
		$content = strip_tags($content, "<table><tr><td><th>");

		$xmlObj = simplexml_load_string($content);
		$fmarr = objectsIntoArray($xmlObj);

		//var_dump($fmarr);

		$aktuell = $fmarr['tr'];

		$grades = "";

		foreach($aktuell as $note){
		$tfach = $note['td'][0];
		$tnote = $note['td'][2];
		$tnoteganz = $note['td'][3];

		if($tfach != null && $tnote != null){
		    $grades[$key][] = array($note['td'][0], $note['td'][2], $note['td'][3]);
		}

		if($note['th'] != '' && !is_array($note['th'])){
		    $key = $note['th'];
		}
		}
    
		// Now, create an XML-Output

		header ("Content-Type:text/xml");  

		echo '<?xml version="1.0"?>';
		echo '<Overview>';

		$terms = array_keys($grades);
		foreach($terms as $term){   
		echo '<Term name="'.$term.'">';
		    foreach($grades[$term] as $grade){
			echo '<Course>';
			    echo '<Title>'.$grade[0].'</Title>';
			    echo '<Grade>'.$grade[1].'</Grade>';
			    echo '<GradeWords>'.$grade[2].'</GradeWords>';
			echo '</Course>';
		    }
		echo '</Term>';
		}
		echo '</Overview>';
	}
        
function fix_latin1_mangled_with_utf8_maybe_hopefully_most_of_the_time($str)
{
    return preg_replace_callback('#[\\xA1-\\xFF](?![\\x80-\\xBF]{2,})#', 'utf8_encode_callback', $str);
}

function getFullCourseName($d){
    include 'getCourses.php';
    return $courses[strtolower($d)][0];
}
        
function parseStudents($file, $course, $year){                
    		$fh = fopen($file[1], "r");
    
		$content = fread($fh, filesize($file[1]));

		fclose($fh);
    
		$content = explode("<body>", $content);

		$content = '<body>'.$content[1];

		$content = explode('</body>', $content);

		$content = trim($content[0]).'</body>';
                
                $content = utf8_encode($content);

		$content = str_replace("&nbsp;", "", $content);
		$content = str_replace("\t", "", $content);
                $content = str_replace("0x", "", $content);
		$content = str_replace("\n", "", $content);
		$content = str_replace("\r", "", $content);
		//$content = str_replace("</td></td>", "</td>", $content);
		$content = str_replace("&Uuml;", "Ü", $content);

		$content = '<?xml version="1.0"?>'.$content;
    
		$content = strip_tags($content, "<body><div><strong><a><img><span><h2>");

                //echo $content;
                
		$xmlObj = simplexml_load_string($content);
		$fmarr = objectsIntoArray($xmlObj);

                $students_arr = $fmarr['div'][0]['div']['div'][1]['div'][1]['div'][1]['div'];
                
		//var_dump($students_arr);
                
                foreach($students_arr as $student){
                    $students[] = array(
                        $student['div'][1]['h2']['strong'], 
                        $student['div'][0]['div']['a']['@attributes']['id']
                    );
                }
                
                //var_dump($students);

		
		// Now, create an XML-Output
                
		header ("Content-Type:text/xml");  

		echo '<?xml version="1.0"?>';
		echo '<Students coursename="'.$course[0].'" course="'.$course[1].'" year="'.$year.'">';

		//$terms = array_keys($grades);
		foreach($students as $s){   
		echo '<Student>';
                        echo '<Name>'.$s[0].'</Name>';
                        echo '<PersId>'.$s[1].'</PersId>';
                        echo '<Photo>http://www.fh-joanneum.at/custom/inc/DBbild.asp?persOid='.$s[1].'</Photo>';
		echo '</Student>';
		}
		echo '</Students>';
                
	}
        
        function parseStudentsOutsideUAS($file, $course, $year){                
    		$fh = fopen($file[1], "r");
    
		$content = fread($fh, filesize($file[1]));

		fclose($fh);
    
		$content = explode("<body>", $content);

		$content = '<body>'.$content[1];

		$content = explode('</body>', $content);

		$content = trim($content[0]).'</body>';
                
                $content = utf8_encode($content);

		$content = str_replace("&nbsp;", "", $content);
		$content = str_replace("\t", "", $content);
                $content = str_replace("0x", "", $content);
		$content = str_replace("\n", "", $content);
		$content = str_replace("\r", "", $content);
		//$content = str_replace("</td></td>", "</td>", $content);
		$content = str_replace("&Uuml;", "Ü", $content);

		$content = '<?xml version="1.0"?>'.$content;
    
		$content = strip_tags($content, "<body><div><strong><a><img><span><h2>");

                //echo $content;
                
		$xmlObj = simplexml_load_string($content);
		$fmarr = objectsIntoArray($xmlObj);
                
                //var_dump($fmarr);

                $students_arr = $fmarr['div'][0]['div']['div'][1]['div'][1]['div'][1]['div'];
                
		//var_dump($students_arr);
                
                foreach($students_arr as $student){
                    $students[] = array(
                        $student['div']['h2']['strong'], 
                        4306937691
                    );
                }
                
                //var_dump($students);

		
		// Now, create an XML-Output
                
                //return false;
                
		header ("Content-Type:text/xml");  

		echo '<?xml version="1.0"?>';
		echo '<Students coursename="'.  getFullCourseName($course).'" course="'.$course.'" year="'.$year.'">';

		//$terms = array_keys($grades);
		foreach($students as $s){   
		echo '<Student>';
                        echo '<Name>'.$s[0].'</Name>';
                        echo '<PersId>'.$s[1].'</PersId>';
                        echo '<Photo>http://www.fh-joanneum.at/custom/inc/DBbild.asp?persOid='.$s[1].'</Photo>';
		echo '</Student>';
		}
		echo '</Students>';
                
	}

function parseExams($file){
    		$fh = fopen($file[1], "r");
    
		$content = fread($fh, filesize($file[1]));

		fclose($fh);
    
		$content = explode("examsTable", $content);

		$content = '<table cellpadding="3" cellspacing="0" class="list" id="'.$content[1];

		$content = explode('</table>', $content);

		$content = trim($content[0]).'</table>';

		$content = str_replace("&nbsp;", "", $content);
		$content = str_replace("\t", "", $content);
		$content = str_replace("\n", "", $content);
		$content = str_replace("\r", "", $content);
		$content = str_replace("</td></td>", "</td>", $content);
		$content = str_replace("&Uuml;", "Ü", $content);
		$content = str_replace("&uuml;", "ü", $content);
		$content = str_replace("&ouml;", "ö", $content);
		$content = str_replace("<br />", " ", $content);

		$content = '<?xml version="1.0"?>'.$content;
    
		$content = strip_tags($content, "<table><tr><td><th>");

		$xmlObj = simplexml_load_string($content);
		$fmarr = objectsIntoArray($xmlObj);

		//var_dump($fmarr);

		$aktuell = $fmarr['tr'];

		//var_dump($aktuell);exit();

		$exams = "";

		foreach($aktuell as $exam){
			$tfach = $exam['td'][1];
			$ttyp = $exam['td'][2];
			$tmodus = $exam['td'][5];
			$tdatum = $exam['td'][7];
			$tbis = $exam['td'][9];

		if($tfach != null && $tbis != null){
		    $exams[$key][] = array($tfach, $ttyp, $tmodus, $tdatum, $tbis);
		}

		if($exam['th'] != '' && !is_array($exam['th'])){
		    $key = $exam['th'];
		}
		}
    
		// Now, create an XML-Output

		header ("Content-Type:text/xml");  

		echo '<?xml version="1.0"?>';
		echo '<Overview>';

		unset($exam);

		$terms = array_keys($exams);
		foreach($terms as $term){   
		echo '<Term name="'.$term.'">';
		    foreach($exams[$term] as $exam){
			echo '<Exam>';
			    echo '<Title>'.$exam[0].'</Title>';
			    echo '<Type>'.$exam[1].'</Type>';
			    echo '<Mode>'.$exam[2].'</Mode>';
			    echo '<Date>'.$exam[3].'</Date>';
			    echo '<RegistrationEnd>'.$exam[4].'</RegistrationEnd>';
			echo '</Exam>';
		    }
		echo '</Term>';
		}
		echo '</Overview>';
	}

?>
